package com.atguigu.gmall.list.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.list.dao.GoodsDao;
import com.atguigu.gmall.list.service.ListService;
import com.atguigu.gmall.model.list.*;
import com.atguigu.gmall.model.product.BaseCategoryView;
import com.atguigu.gmall.model.product.BaseTrademark;
import com.atguigu.gmall.model.product.SkuAttrValue;
import com.atguigu.gmall.model.product.SkuInfo;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ListServiceImpl implements ListService {


    @Autowired
    public RestHighLevelClient restHighLevelClient;
    @Autowired
    public ProductFeignClient productFeignClient;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private RedisTemplate redisTemplate;


    //导入索引
    @Override
    public void upperGoods(Long skuId) {

        //一部手机全部索引手机
        Goods goods = new Goods();

        //1:根据skuId查询SkuInfo 信息
        SkuInfo skuInfo = productFeignClient.getSkuInfo(skuId);
        goods.setId(skuInfo.getId());
        goods.setDefaultImg(skuInfo.getSkuDefaultImg());
        goods.setTitle(skuInfo.getSkuName());
        goods.setPrice(skuInfo.getPrice().doubleValue());
        goods.setCreateTime(new Date());
        //2:根据tmId 查询品牌相关数据
        BaseTrademark baseTrademark = productFeignClient.getBaseTrademark(skuInfo.getTmId());
        goods.setTmId(baseTrademark.getId());
        goods.setTmName(baseTrademark.getTmName());
        goods.setTmLogoUrl(baseTrademark.getLogoUrl());
        //3:根据category3Id查询分类视图
        BaseCategoryView baseCategoryView = productFeignClient.
                getBaseCategoryView(skuInfo.getCategory3Id());
        goods.setCategory1Id(baseCategoryView.getCategory1Id());
        goods.setCategory1Name(baseCategoryView.getCategory1Name());
        goods.setCategory2Id(baseCategoryView.getCategory2Id());
        goods.setCategory2Name(baseCategoryView.getCategory2Name());
        goods.setCategory3Id(baseCategoryView.getCategory3Id());
        goods.setCategory3Name(baseCategoryView.getCategory3Name());
        //4：根据skuId 查询 sku_attr_value   base_attr_info  base_attr_value
        List<SkuAttrValue> skuAttrValuesList = productFeignClient.getSkuAttrValue(skuId);
        //private List<SearchAttr> attrs;//平台属性集合  Stream流 偷天换日
        List<SearchAttr> searchAttrList =
                skuAttrValuesList.stream().map(skuAttrValue -> {
                    SearchAttr searchAttr = new SearchAttr();
                    searchAttr.setAttrId(skuAttrValue.getBaseAttrInfo().getId());
                    searchAttr.setAttrName(skuAttrValue.getBaseAttrInfo().getAttrName());
                    searchAttr.setAttrValue(skuAttrValue.getBaseAttrValue().getValueName());
                    return searchAttr;
                }).collect(Collectors.toList());
        goods.setAttrs(searchAttrList);
        //保存索引库
        goodsDao.save(goods);
    }

    //删除索引
    @Override
    public void lowerGoods(Long skuId) {
        //ES 官方高级客户端的删除方式
         /*
        DeleteRequest deleteRequest = new DeleteRequest();
        deleteRequest.index("goods");
        deleteRequest.id(skuId.toString());
        try {
            restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        //2：SpringDataES  删除方式   Mybatis-Plus  相同的
        goodsDao.deleteById(skuId);
    }

    //增加 热度 评分
    @Override
    public void hotScore(Long skuId) {
        //1:通过缓存 进行缓存   100 更新一次 ES
        Double hotScore = redisTemplate.opsForZSet().incrementScore("hotScore", skuId, 1);

        if (hotScore % 10 == 0) {

            //1:查询 ES库 此商品的评分
            Optional<Goods> byId = goodsDao.findById(skuId);
            Goods goods = byId.get();
            //2：将此商品 评分加分
            goods.setHotScore(Math.round(hotScore));
            //3：此商品保存回ES库
            goodsDao.save(goods);
        }
    }

    //开始搜索ES索引库
    @Override
    public SearchResponseVo search(SearchParam searchParam) {

        SearchResponseVo vo = null;

        try {
            //1：构建搜索请求对象
            SearchRequest searchRequest = buildSearchRequest(searchParam);
            //2：执行搜索
            SearchResponse searchResponse = restHighLevelClient.
                    search(searchRequest, RequestOptions.DEFAULT);
            //3；解析结果对象
            vo = parseSearchResponse(searchResponse);

//            vo.setTrademarkList(searchParam.get);

            //当前页
            vo.setPageNo(searchParam.getPageNo());
            //每页数
            vo.setPageSize(searchParam.getPageSize());//每页5  共 16条
            //总页数 == （总条数+每页数 - 1 /每页数
            vo.setTotalPages((vo.getTotal() + vo.getPageSize() - 1) / vo.getPageSize());
        } catch (IOException e) {
            e.printStackTrace();
        }


        return vo;
    }

    //解析结果
    private SearchResponseVo parseSearchResponse(SearchResponse searchResponse) {
        SearchResponseVo vo = new SearchResponseVo();

        SearchHits hits = searchResponse.getHits();


        //获取聚合对象
        Map<String, Aggregation> stringAggregationMap = searchResponse.getAggregations().asMap();
        //解析平台属性
        ParsedNested aggAttrs = (ParsedNested) stringAggregationMap.get("aggAttrs");
        ParsedLongTerms aggAttrId = aggAttrs.getAggregations().get("aggAttrId");
        List<SearchResponseAttrVo> attrsList = aggAttrId.getBuckets().stream().map(bucket -> {
            SearchResponseAttrVo attrVo = new SearchResponseAttrVo();
            //平台属性Id
            attrVo.setAttrId(Long.parseLong(bucket.getKeyAsString()));
            ParsedStringTerms aggAttrName = ((Terms.Bucket) bucket).getAggregations().get("aggAttrName");
            attrVo.setAttrName(aggAttrName.getBuckets().get(0).getKeyAsString());
            //品台属性值
            ParsedStringTerms aggAttrValue = ((Terms.Bucket) bucket).getAggregations().get("aggAttrValue");
            List<String> attrValueList = aggAttrValue.getBuckets().stream()
                    .map(Terms.Bucket::getKeyAsString).collect(Collectors.toList());
            attrVo.setAttrValueList(attrValueList);
            return attrVo;
        }).collect(Collectors.toList());

        vo.setAttrsList(attrsList);

        //拿到一个聚合，这聚合是个接口
        ParsedLongTerms aggTmId = (ParsedLongTerms) stringAggregationMap.get("aggTmId");
        //解析品牌集合
        List<SearchResponseTmVo> trademarkList = aggTmId.getBuckets().stream().map(bucket -> {
            SearchResponseTmVo tmVo = new SearchResponseTmVo();
            tmVo.setTmId(Long.parseLong(bucket.getKeyAsString()));
            //品牌名称
            ParsedStringTerms aggTmName = ((Terms.Bucket) bucket).getAggregations().get("aggTmName");
            tmVo.setTmName(aggTmName.getBuckets().get(0).getKeyAsString());
            //品牌Logo
            ParsedStringTerms aggTmLogoUrl = ((Terms.Bucket) bucket).getAggregations().get("aggTmLogoUrl");
            tmVo.setTmLogoUrl(aggTmLogoUrl.getBuckets().get(0).getKeyAsString());

            return tmVo;
        }).collect(Collectors.toList());
        vo.setTrademarkList(trademarkList);

        //商品结果集
        SearchHit[] hits1 = hits.getHits();
        List<Goods> goodsList = Arrays.stream(hits1).map(hit -> {
            Goods goods = JSONObject.parseObject(hit.getSourceAsString(), Goods.class);

            //解析高亮的值
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if(null != highlightFields && highlightFields.size() > 0){
                HighlightField title = highlightFields.get("title");
                if (title != null){
                    String hname = title.fragments()[0].toString();
                    goods.setTitle(hname);
                    System.out.println(hname);
                }
            }

            return goods;
        }).collect(Collectors.toList());

        //商品信息
        vo.setGoodsList(goodsList);
        //分页 总条数
        vo.setTotal(hits.getTotalHits());
        System.out.println(hits.getTotalHits());

        return vo;
    }

    //  构建  搜索    请求对象
    private SearchRequest buildSearchRequest(SearchParam searchParam) {
        //条件对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //当多个条件的时候  组合条件对象
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //关键词  类似于手机  电视
        String keyword = searchParam.getKeyword();
        if (!StringUtils.isEmpty(keyword)) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("title", keyword).operator(Operator.AND )
            );//.operator(Operator.AND )  取交集
        } else {
            //搜索全部数据
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }
        //品牌  过滤条件   品牌ID:品牌名称
        String trademark = searchParam.getTrademark();
        if (!StringUtils.isEmpty(trademark)) {
            String[] t = StringUtils.split(trademark, ":");
            boolQueryBuilder.filter(QueryBuilders.termQuery("tmId", t[0]));
        }
        //一二三级分类
        Long category1Id = searchParam.getCategory1Id();
        if (category1Id != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("category1Id", category1Id));
        }
        Long category2Id = searchParam.getCategory2Id();
        if (category2Id != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("category2Id", category2Id));
        }
        Long category3Id = searchParam.getCategory3Id();
        if (category3Id != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("category3Id", category3Id));
        }
        //4:平台属性ID：品台属性值：平台属性名称
        String[] props = searchParam.getProps();
        if (null != props && props.length > 0) {
            // 父  大爷
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

            for (String prop : props) {
                String[] p = prop.split(":");
                BoolQueryBuilder subBoolQuery = QueryBuilders.boolQuery();
                subBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", p[0]));
                subBoolQuery.must(QueryBuilders.termQuery("attrs.attrValue", p[1]));
                boolQuery.must(QueryBuilders.nestedQuery("attrs", subBoolQuery, ScoreMode.None));

            }
            //父
            boolQueryBuilder.filter(boolQuery);

        }

        //构建条件对象
        searchSourceBuilder.query(boolQueryBuilder);
        //排序
        String order = searchParam.getOrder();
        if (!StringUtils.isEmpty(order)) {
            String[] o = order.split(":");
            String field = null;
            switch (o[0]) {
                case "1":
                    field = "hotScore";
                    break;
                case "2":
                    field = "price";
                    break;

            }
            searchSourceBuilder.sort(field, o[1].
                    equalsIgnoreCase(SortOrder.ASC.toString()) ? SortOrder.ASC : SortOrder.DESC);
        }


        //分页
        Integer pageNo = searchParam.getPageNo();
        Integer pageSize = searchParam.getPageSize();
        searchSourceBuilder.from((pageNo - 1) * pageSize);//开始行  limit 开始行,每页数
        searchSourceBuilder.size(pageSize);


        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder
                .field("title")
                .preTags("<span style='color:red'>")
                .postTags("</span>");

        searchSourceBuilder.highlighter(highlightBuilder);


        //品牌聚合  简单的
        searchSourceBuilder.aggregation(
                AggregationBuilders.terms("aggTmId").field("tmId")
                        .subAggregation(AggregationBuilders.terms("aggTmName").field("tmName"))
                        .subAggregation(AggregationBuilders.terms("aggTmLogoUrl").field("tmLogoUrl"))
        );

        //平台属性 聚合  超级难
        searchSourceBuilder.aggregation(
                AggregationBuilders.nested("aggAttrs", "attrs")
                        .subAggregation(AggregationBuilders.terms("aggAttrId").field("attrs.attrId")
                                .subAggregation(AggregationBuilders.terms("aggAttrName").field("attrs.attrName"))
                                .subAggregation(AggregationBuilders.terms("aggAttrValue").field("attrs.attrValue"))));

        //打印DSL语句
        System.out.println(searchSourceBuilder.toString());


        SearchRequest searchRequest = new SearchRequest();//请求 ES
        //设置要搜索的索引库的名称
        searchRequest.indices("goods");//Mysql  数据库
        //构建搜索条件对象
        searchRequest.source(searchSourceBuilder);

        return searchRequest;

    }
}
